﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//----------------------------------
using WeifenLuo.WinFormsUI.Docking;
using Microsoft.Reporting.WinForms;


using Entity;

namespace SalesVMT
{
    public partial class frmReport : DockContent
    {
        private UIReportViewer customMessages = null;

        private bool LoadedFlag = false;
        public frmReport()
        {
            InitializeComponent();
        }

        public frmReport(string ReportType, string[] Args)
        {
            InitializeComponent();
            customizeMessages();
            customizeReportViewer();

            switch (ReportType)
            {
                case "PHIEU NHAP HANG":
                    this.TabText = this.Text = Args[1];
                    PhieuNhapHang(Args[0]);
                    break;
                case "PHIEU CHI":
                    this.TabText = this.Text = Args[1];
                    PhieuChi(Args[0]);
                    break;
                case "BAO GIA BAN BUON":
                    this.TabText = this.Text = "Báo giá bán buôn";
                    BaoGiaBanBuon(Args[0]);
                    break;
                case "BAO GIA BAN LE":
                    this.TabText = this.Text = "Báo giá bán lẻ";
                    BaoGiaBanLe(Args[0]);
                    break;
                case "CONG NO NCC":
                    this.TabText = this.Text = Args[1];
                    CongNoNCC(Args[0]);
                    break;
                case "DON DAT HANG DA MUA":
                    this.TabText = this.Text = "Đơn đặt hàng đã mua";
                    DonDatHangDaMua(Args[0], Args[1], Args[2]);
                    break;

                case "PHIEU XUAT HANG":
                    this.TabText = this.Text = Args[1];
                    PhieuXuatHang(Args[0]);
                    break;
                case "PHIEU THU":
                    this.TabText = this.Text = Args[1];
                    PhieuThu(Args[0]);
                    break;
                case "DON DAT HANG DA BAN":
                    this.TabText = this.Text = "Đơn đặt hàng đã bán";
                    DonDatHangDaBan(Args[0], Args[1], Args[2]);
                    break;
                case "CONG NO KH":
                    this.TabText = this.Text = Args[1];
                    CongNoKH(Args[0]);
                    break;
            }
        }
        private void PhieuNhapHang(string ReceiptID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.PhieuNhapHang.rdlc";
            DataTable _dt = new DataTable();

            _dt = ReceiptDB.GetOne(Convert.ToInt32(ReceiptID)).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Receipt", _dt));
            decimal _remaining=Convert.ToDecimal(_dt.Rows[0]["Receipt_Remaining"]);
            _dt = ReceiptDetailsDB.GetAllByReceipt(Convert.ToInt32(ReceiptID)).Tables[0];

            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_ReceiptDetails", _dt));


            decimal _total=0;
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                _total += Convert.ToDecimal(_dt.Rows[i]["ReceiptDetails_Total"]);
            }
            ReadNumberToString(_total + _remaining);

            LoadCompany();
            this.reportViewer1.RefreshReport();
        }
        private void PhieuXuatHang(string ShipmentID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.PhieuXuatHang.rdlc";
            DataTable _dt = new DataTable();

            _dt = ShipmentDB.GetOne(Convert.ToInt32(ShipmentID)).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Shipment", _dt));
            decimal _remaining = Convert.ToDecimal(_dt.Rows[0]["Shipment_Remaining"]);
            _dt = ShipmentDetailsDB.GetAllByShipment(Convert.ToInt32(ShipmentID)).Tables[0];

            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_ShipmentDetails", _dt));


            decimal _total = 0;
            int n = _dt.Rows.Count;
            for (int i = 0; i < n; i++)
            {
                _total += Convert.ToDecimal(_dt.Rows[i]["ShipmentDetails_Total"]);
            }
            ReadNumberToString(_total + _remaining);


            LoadCompany();
            this.reportViewer1.RefreshReport();
        }
        private void PhieuChi(string SpendID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.PhieuChi.rdlc";
            DataTable _dt = new DataTable();

            _dt = SpendDB.GetOne(Convert.ToInt32(SpendID)).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Spend", _dt));

            decimal _total = Convert.ToDecimal(_dt.Rows[0]["Spend_Total"]);
            ReadNumberToString(_total);

            //_dt = SpendDetailsDB.GetAllBySpend(Convert.ToInt32(SpendID)).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_SpendDetails", _dt));

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void PhieuThu(string IncomeID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.PhieuThu.rdlc";
            DataTable _dt = new DataTable();

            _dt = IncomeDB.GetOne(Convert.ToInt32(IncomeID)).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Income", _dt));

            decimal _total = Convert.ToDecimal(_dt.Rows[0]["Income_Total"]);
            ReadNumberToString(_total);

            //_dt = IncomeDetailsDB.GetAllByIncome(Convert.ToInt32(IncomeID)).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_IncomeDetails", _dt));

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void ReadNumberToString(decimal total)
        {
            string ByString = clsNumberToString.NumberToString(total.ToString("##0"));
            ByString += CompanyDB.GetInfo(1).Company_Currency;
            ReportParameter rp1 = new ReportParameter("ByString", ByString);
            this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp1 });
        }
        private void BaoGiaBanBuon(string ItemID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.BaoGiaBanBuon.rdlc";
            if(Convert.ToInt32(ItemID)>0)
                this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Item", ItemDB.GetOne(Convert.ToInt32(ItemID)).Tables[0]));
            else
                this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Item", ItemDB.GetAll().Tables[0]));
            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void BaoGiaBanLe(string ItemID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.BaoGiaBanLe.rdlc";

            if (Convert.ToInt32(ItemID) > 0)
                this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Item", ItemDB.GetOne(Convert.ToInt32(ItemID)).Tables[0]));
            else
                this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Item", ItemDB.GetAll().Tables[0]));

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void CongNoNCC(string ProviderID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.CongNoNCC.rdlc";

            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Receipt", ReceiptDB.GetAllByProviderForSpend(Convert.ToInt32(ProviderID)).Tables[0]));

            ReportParameter rp1, rp2, rp3, rp4;
            string _code, _name, _address, _taxno;
            int _ProviderID = Convert.ToInt32(ProviderID);
            if (_ProviderID == 0)
            {
                _code = "";
                _name = "";
                _address = "";
                _taxno = "";
            }
            else
            {
                _code = ProviderDB.GetInfo(_ProviderID).Provider_Code;
                _name = ProviderDB.GetInfo(_ProviderID).Provider_Name;
                _address = ProviderDB.GetInfo(_ProviderID).Provider_Address;
                _taxno = ProviderDB.GetInfo(_ProviderID).Provider_TaxNo;
            }
            rp1 = new ReportParameter("Provider_Code", _code);
            rp2 = new ReportParameter("Provider_Name", _name);
            rp3 = new ReportParameter("Provider_Address", _address);
            rp4 = new ReportParameter("Provider_TaxNo", _taxno);
            this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp1, rp2, rp3, rp4 });

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void CongNoKH(string CustomerID)
        {
            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.CongNoKH.rdlc";

            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Shipment", ShipmentDB.GetAllByCustomerForIncome(Convert.ToInt32(CustomerID)).Tables[0]));

            ReportParameter rp1, rp2, rp3, rp4;
            string _code, _name, _address, _taxno;
            int _CustomerID = Convert.ToInt32(CustomerID);
            if (_CustomerID == 0)
            {
                _code = "";
                _name = "";
                _address = "";
                _taxno = "";
            }
            else
            {
                _code = CustomerDB.GetInfo(_CustomerID).Customer_Code;
                _name = CustomerDB.GetInfo(_CustomerID).Customer_Name;
                _address = CustomerDB.GetInfo(_CustomerID).Customer_Address;
                _taxno = CustomerDB.GetInfo(_CustomerID).Customer_TaxNo;
            }
            rp1 = new ReportParameter("Customer_Code", _code);
            rp2 = new ReportParameter("Customer_Name", _name);
            rp3 = new ReportParameter("Customer_Address", _address);
            rp4 = new ReportParameter("Customer_TaxNo", _taxno);
            this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp1, rp2, rp3, rp4 });

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void DonDatHangDaMua(string ProviderID, string FromDate, string ToDate)
        {
            int _ProviderID = Convert.ToInt32(ProviderID);
            DateTime _FromDate = DateTime.ParseExact(FromDate, "dd/MM/yyyy", null);
            DateTime _ToDate = DateTime.ParseExact(ToDate, "dd/MM/yyyy", null);

            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.DonDatHangDaMua.rdlc";

            DataTable _dt = ReceiptDB.GetOrderPurchaseForReport(_ProviderID, _FromDate, _ToDate).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Receipt", _dt));

            ReportParameter rp1, rp2, rp3;
            string _Name;
            if (_ProviderID == 0)
                _Name = "Tất cả";
            else
                _Name = ProviderDB.GetInfo(_ProviderID).Provider_Name;
            rp1 = new ReportParameter("Provider_Name", _Name);
            rp2 = new ReportParameter("FromDate", FromDate);
            rp3 = new ReportParameter("ToDate", ToDate);
            this.reportViewer1.LocalReport.SetParameters(new ReportParameter[]{rp1,rp2,rp3});

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        private void DonDatHangDaBan(string CustomerID, string FromDate, string ToDate)
        {
            int _CustomerID = Convert.ToInt32(CustomerID);
            DateTime _FromDate = DateTime.ParseExact(FromDate, "dd/MM/yyyy", null);
            DateTime _ToDate = DateTime.ParseExact(ToDate, "dd/MM/yyyy", null);

            reportViewer1.LocalReport.ReportEmbeddedResource = "SalesVMT.Report.DonDatHangDaBan.rdlc";

            DataTable _dt = ShipmentDB.GetOrderSalesForReport(_CustomerID, _FromDate, _ToDate).Tables[0];
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Shipment", _dt));

            ReportParameter rp1, rp2, rp3;
            string _Name;
            if (_CustomerID == 0)
                _Name = "Tất cả";
            else
                _Name = CustomerDB.GetInfo(_CustomerID).Customer_Name;
            rp1 = new ReportParameter("Customer_Name", _Name);
            rp2 = new ReportParameter("FromDate", FromDate);
            rp3 = new ReportParameter("ToDate", ToDate);
            this.reportViewer1.LocalReport.SetParameters(new ReportParameter[] { rp1, rp2, rp3 });

            LoadCompany();

            this.reportViewer1.RefreshReport();
        }
        void LoadCompany()
        {
            this.reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("Report_Company", CompanyDB.GetOne(1).Tables[0]));
        }
        private void frmReport_Load(object sender, EventArgs e)
        {
            this.reportViewer1.Messages = this.customMessages;
            LoadedFlag = true;
        }
        
        private void frmReport_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = !LoadedFlag;
        }
        private void reportViewer1_RenderingComplete(object sender, RenderingCompleteEventArgs e)
        {
            this.reportViewer1.SetDisplayMode(DisplayMode.PrintLayout);
            this.reportViewer1.ZoomMode = ZoomMode.Percent;
        }
        #region customizeMessages

        private void customizeMessages()
        {
            this.customMessages = new UIReportViewer(this.reportViewer1.Messages);
            this.customMessages.FindButtonText = "Tìm kiếm";
            this.customMessages.FindButtonToolTip = "Tìm kiếm";
            this.customMessages.FindNextButtonText = "Tìm kiếm thêm";
            this.customMessages.FindNextButtonToolTip = "Tìm kiếm thêm";
            this.customMessages.SearchTextBoxToolTip = @"Gõ từ khoá vào đây";
            this.customMessages.TextNotFound = @"Không tìm thấy";
            this.customMessages.NoMoreMatches = @"Không tìm thấy kết quả";
            this.customMessages.BackButtonToolTip = @"Trở lại";
            this.customMessages.BackMenuItemText = @"Trở lại";
            this.customMessages.DocumentMapButtonToolTip = @"DocumentMap";
            this.customMessages.DocumentMapMenuItemText = @"DocumentMap";
            this.customMessages.ExportButtonToolTip = @"Xuất dữ liệu";
            this.customMessages.ExportMenuItemText = @"Xuất dữ liệu";
            this.customMessages.FalseValueText = @"Sai";
            this.customMessages.FirstPageButtonToolTip = @"Trang đầu";
            this.customMessages.LastPageButtonToolTip = @"Trang cuối";
            this.customMessages.NextPageButtonToolTip = @"Trang tiếp theo";
            this.customMessages.PageOf = @"/";
            this.customMessages.PageSetupButtonToolTip = @"Đặt khổ giấy";
            this.customMessages.PageSetupMenuItemText = @"Đặt khổ giấy";
            this.customMessages.ParameterAreaButtonToolTip = @"Parameter";
            this.customMessages.PasswordPrompt = @"Password";
            this.customMessages.PreviousPageButtonToolTip = @"Trang trước";
            this.customMessages.PrintButtonToolTip = @"In báo cáo";
            this.customMessages.PrintLayoutButtonToolTip = @"Layout";
            this.customMessages.PrintLayoutMenuItemText = @"Layout";
            this.customMessages.PrintMenuItemText = @"In báo cáo";
            this.customMessages.ProgressText = @"Đang nạp dữ liệu";
            this.customMessages.RefreshButtonToolTip = @"Nạp lại báo cáo";
            this.customMessages.RefreshMenuItemText = @"Nạp lại báo cáo";
            this.customMessages.SelectAll = @"Select All";
            this.customMessages.SelectAValue = @"Select";
            this.customMessages.StopButtonToolTip = @"Dừng lại";
            this.customMessages.StopMenuItemText = @"Dừng lại";
            this.customMessages.TotalPagesToolTip = @"Tổng số trang";
            this.customMessages.TrueValueText = @"Đúng";
            this.customMessages.UserNamePrompt = @"UserName";
            this.customMessages.ViewReportButtonText = @"Xem báo cáo";
            this.customMessages.ViewReportButtonToolTip = @"Xem báo cáo";
            this.customMessages.ZoomControlToolTip = @"Zoom";
            this.customMessages.ZoomMenuItemText = @"Zoom";
            this.customMessages.ZoomToPageWidth = @"Xem theo độ rộng";
            this.customMessages.ZoomToWholePage = @"Xem toàn bộ";

        }

        #endregion

        #region customizeReportViewer

        private void customizeReportViewer()
        {
            ToolStrip toolStrip = this.ToolStrip;

            if (toolStrip != null)
            {
                toolStrip.ImageList = this.reportViewerImageList;

                toolStrip.Items["find"].ImageKey = "btnFind.Image";
                toolStrip.Items["findNext"].ImageKey = "btnFindNext.Image";

                int zoomPos = toolStrip.Items.IndexOfKey("zoom");
                if (zoomPos >= 0)
                {
                    toolStrip.Items.Insert(zoomPos + 1, this.addDefaultSeparator("additionalSeparator1"));
                    toolStrip.Items.Insert(zoomPos + 1, this.addDefaultLabel("lblSeparator", String.Empty, 100));
                    toolStrip.Items.Insert(zoomPos + 1, this.addDefaultSeparator("additionalSeparator2"));
                    toolStrip.Items.Insert(zoomPos + 1, this.addDefaultButton("btnClose", "Đóng", "btnClose.Image", new EventHandler(ButtonClose)));
                    toolStrip.Items.Insert(zoomPos + 1, this.addDefaultButton("btnHelp", "Trợ giúp", "btnHelp.Image", null));
                    toolStrip.Items.Insert(zoomPos + 1, this.addDefaultSeparator("additionalSeparator3"));
                }

                ToolStripDropDownButton exportButton = toolStrip.Items["export"] as ToolStripDropDownButton;
                if (exportButton != null)
                    exportButton.DropDownOpened += new EventHandler(this.OnExportOpened);
            }
        }

        private ToolStripButton addDefaultButton(string name, string text, string imageResource, EventHandler eventHandler)
        {
            ToolStripButton result = new ToolStripButton();

            result.Name = name;
            result.Size = new System.Drawing.Size(23, 22);
            result.Text = text;

            if (imageResource == String.Empty)
                result.DisplayStyle = ToolStripItemDisplayStyle.Text;
            else
            {
                result.DisplayStyle = ToolStripItemDisplayStyle.Image;
                result.ImageKey = imageResource;
            }

            if (eventHandler != null)
                result.Click += eventHandler;

            return result;
        }

        private ToolStripLabel addDefaultLabel(string name, string text)
        {
            return addDefaultLabel(name, text, 0);
        }

        private ToolStripLabel addDefaultLabel(string name, string text, int width)
        {
            ToolStripLabel result = new ToolStripLabel();

            result.Name = name;
            result.Text = text;

            result.AutoSize = (width <= 0);

            if (!result.AutoSize)
                result.Size = new System.Drawing.Size(width, 22);

            return result;
        }

        private ToolStripSeparator addDefaultSeparator(string name)
        {
            ToolStripSeparator result = new ToolStripSeparator();

            result.Name = name;
            result.Size = new System.Drawing.Size(6, 25);

            return result;
        }

        private TClass FindToolStrip<TClass>(Control control)
            where TClass : System.Windows.Forms.Control
        {
            if (control == null)
                return default(TClass);
            else if (control is TClass)
                return (TClass)control;
            else
            {
                TClass result = default(TClass);
                foreach (Control embedded in control.Controls)
                {
                    if (result == null)
                        result = FindToolStrip<TClass>(embedded);
                }

                return result;
            }
        }

        private void ButtonClose(object sender, EventArgs e)
        {
            this.Close();
        }
        private void OnExportOpened(object sender, EventArgs e)
        {
            if (sender is ToolStripDropDownButton)
            {
                ToolStripDropDownButton button = (ToolStripDropDownButton)sender;

                foreach (ToolStripItem item in button.DropDownItems)
                {
                    RenderingExtension extension = (RenderingExtension)item.Tag;
                    if (extension != null)
                    {
                        switch (extension.Name)
                        {
                            case "Excel":
                                item.Image = this.reportViewerImageList.Images["btnExcel.Image"];
                                break;
                            case "PDF":
                                item.Image = this.reportViewerImageList.Images["btnPdf.Image"];
                                break;
                        }
                    }
                }
            }
        }
        private ToolStrip ToolStrip
        {
            get { return this.FindToolStrip<ToolStrip>(this.reportViewer1); }
        }
        #endregion




    }
}